package com.asset.dispoal.file.bank.domain.service.command;

import com.asset.dispoal.file.bank.domain.db.mapper.FileBankMapper;
import com.asset.dispoal.file.bank.domain.dto.FileBankDetailExportTemplate;
import com.asset.dispoal.file.bank.dto.FileBankDetailRequest;
import lombok.SneakyThrows;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tech.mhuang.pacebox.core.date.DateTimeUtil;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.id.BaseIdeable;
import tech.mhuang.pacebox.core.util.CollectionUtil;
import tech.mhuang.pacebox.springboot.core.spring.util.DataUtil;
import tech.mhuang.pacebox.springboot.protocol.Result;

import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
public class FileBankDetailExcelDataSaveCommand implements BaseCommand<Map<String, Object>, Result> {

    @Autowired
    private BaseIdeable<String> idWorker;

    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    @SneakyThrows
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Result execute(Map<String, Object> map) {
        String bankId = (String) map.get("bankId");
        List<FileBankDetailExportTemplate> bsDataDetailExportTemplateList = (List<FileBankDetailExportTemplate>) map.get("dataList");
        if (CollectionUtil.isEmpty(bsDataDetailExportTemplateList)) {
            return Result.faild("导入数据为空");
        }
        SqlSession sqlSession = this.sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
        FileBankMapper mapper = this.sqlSessionTemplate.getMapper(FileBankMapper.class);
        FileBankDetailExportTemplate last = bsDataDetailExportTemplateList.get(bsDataDetailExportTemplateList.size() - 1);
        for (FileBankDetailExportTemplate data : bsDataDetailExportTemplateList) {
            LocalDate date = LocalDate.of(data.getYear(), data.getMonth(), data.getDay());
            Date dateKey = DateTimeUtil.localDateToStartDate(date);
            FileBankDetailRequest request = DataUtil.copyTo(data, FileBankDetailRequest.class);
            request.setId(idWorker.generateId());
            request.setBankId(bankId);
            request.setRecordDate(dateKey);
            mapper.saveDetail(request);
        }
        mapper.modifyAmount(last.getSurplusAmount(), bankId);
        sqlSession.flushStatements();
        sqlSession.commit();
        sqlSession.clearCache();
        sqlSession.close();
        return Result.ok();
    }
}
